package com.pz.gulimall.search.exception;

import com.pz.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.pz.gulimall.search.controller")
public class GlobalControllerAdvice {
    //处理所有的异常
    @ExceptionHandler(value = Throwable.class)
    public R handleAllException(Throwable throwable){
        log.error("有未知异常-->{}", throwable.getMessage());
        return R.error(throwable.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class) //指定扫描的异常
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> res = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            res.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(400,"数据校验出现问题").put("data", res);
    }
}
